<template>
  <div class="admin-dashboard">
    <el-container>
      <el-header class="header">
        <div class="header-left">
          <img class="system-logo" src="/logo_02.png" alt="系统 Logo" />
          <h2>管理员后台</h2>
        </div>
        <div class="header-right">
          <el-dropdown @command="handleCommand">
            <span class="user-info">
              <el-avatar :size="32" :src="userAvatar" />
              <span class="username">{{ currentUser.username }}</span>
              <el-icon><arrow-down /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人资料</el-dropdown-item>
                <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <el-container>
        <el-aside width="200px" class="sidebar">
          <el-menu
            :default-active="activeMenu"
            class="sidebar-menu"
            @select="handleMenuSelect"
          >
            <el-menu-item index="dashboard">
              <el-icon><house /></el-icon>
              <span>仪表板</span>
            </el-menu-item>
            <el-menu-item index="users">
              <el-icon><user /></el-icon>
              <span>用户管理</span>
            </el-menu-item>
            <el-menu-item index="sensitive-words">
              <el-icon><warning /></el-icon>
              <span>敏感词管理</span>
            </el-menu-item>
            <el-menu-item index="corpus">
              <el-icon><document /></el-icon>
              <span>语料库管理</span>
            </el-menu-item>
          </el-menu>
        </el-aside>

        <el-main class="main-content">
          <!-- 仪表板概览 -->
          <div v-if="activeMenu === 'dashboard'" class="dashboard-overview">
            <h3>系统概览</h3>
            <el-row :gutter="20" class="stats-cards">
              <el-col :span="6">
                <el-card class="stat-card">
                  <div class="stat-content">
                    <div class="stat-icon user-icon">
                      <el-icon><user /></el-icon>
                    </div>
                    <div class="stat-info">
                      <div class="stat-number">{{ stats.totalUsers }}</div>
                      <div class="stat-label">总用户数</div>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card class="stat-card">
                  <div class="stat-content">
                    <div class="stat-icon admin-icon">
                      <el-icon><user-filled /></el-icon>
                    </div>
                    <div class="stat-info">
                      <div class="stat-number">{{ stats.adminUsers }}</div>
                      <div class="stat-label">管理员数</div>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card class="stat-card">
                  <div class="stat-content">
                    <div class="stat-icon word-icon">
                      <el-icon><warning /></el-icon>
                    </div>
                    <div class="stat-info">
                      <div class="stat-number">{{ stats.sensitiveWords }}</div>
                      <div class="stat-label">敏感词数</div>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card class="stat-card">
                  <div class="stat-content">
                    <div class="stat-icon data-icon">
                      <el-icon><document /></el-icon>
                    </div>
                    <div class="stat-info">
                      <div class="stat-number">{{ stats.sentencePairs }}</div>
                      <div class="stat-label">句子对数</div>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>

            <div class="recent-activity">
              <h4>最近活动</h4>
              <el-card>
                <div ref="chartRef" class="activity-chart-container"></div>
              </el-card>
            </div>
          </div>

          <!-- 用户管理 -->
          <UserManagement v-if="activeMenu === 'users'" />

          <!-- 敏感词管理 -->
          <SensitiveWordManagement v-if="activeMenu === 'sensitive-words'" />

          <!-- 语料库管理 -->
          <CorpusManagement v-if="activeMenu === 'corpus'" />
        </el-main>
      </el-container>
    </el-container>

    <!-- 个人资料对话框 -->
    <el-dialog v-model="profileDialogVisible" title="个人资料" width="640px">
      <div class="profile-content">
        <div class="avatar-section">
          <div class="avatar-wrapper">
            <el-avatar :size="96" :src="avatarPreview || profileUser.avatar_url" shape="circle" />
          </div>
          <div class="avatar-actions">
            <el-upload
              class="avatar-uploader"
              :before-upload="beforeAvatarUpload"
              :show-file-list="false"
              :http-request="customAvatarUpload"
              accept="image/png,image/jpeg"
            >
              <el-button type="primary" :loading="uploading">上传头像</el-button>
            </el-upload>
            <div class="hint">仅支持 jpg/png，大小不超过 2MB</div>
          </div>
        </div>
        <el-form :model="profileForm" :rules="profileRules" ref="profileFormRef" label-width="100px" class="profile-form">
          <el-form-item label="用户名">
            <el-input v-model="profileForm.username" readonly />
        </el-form-item>
        <el-form-item label="邮箱">
            <el-input v-model="profileForm.email" readonly />
          </el-form-item>
          <el-form-item label="个人简介" prop="bio">
            <el-input
              v-model="profileForm.bio"
              type="textarea"
              :rows="5"
              maxlength="500"
              show-word-limit
              placeholder="介绍一下自己..."
            />
        </el-form-item>
        <el-form-item label="角色">
          <el-tag type="danger">管理员</el-tag>
        </el-form-item>
      </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="profileDialogVisible = false" :disabled="profileLoading">取消</el-button>
          <el-button type="primary" @click="handleUpdateProfile" :loading="profileLoading">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown, House, User, Warning, UserFilled, Document } from '@element-plus/icons-vue'
import { auth, admin } from '@/api'
import * as echarts from 'echarts'
import UserManagement from './UserManagement.vue'
import SensitiveWordManagement from './SensitiveWordManagement.vue'
import CorpusManagement from './CorpusManagement.vue'

const router = useRouter()
const activeMenu = ref('dashboard')

/**
 * 当前登录用户信息，读取自 localStorage 并保持响应式
 */
const currentUser = ref(JSON.parse(localStorage.getItem('user') || '{}'))

/**
 * 解析后端基地址，用于拼接 /static 资源地址
 * @returns {string} 后端 Origin
 */
const backendOrigin = (() => {
  try {
    const raw = (auth && auth.instance && auth.instance.defaults && auth.instance.defaults.baseURL) || ''
    const url = new URL(raw)
    return `${url.protocol}//${url.hostname}${url.port ? ':' + url.port : ''}`
  } catch {
    return ''
  }
})()

/**
 * 归一化静态资源 URL，支持相对路径与绝对路径
 * @param {string} url 可能为相对或绝对的图片地址
 * @returns {string} 绝对可用的图片地址
 */
const normalizeStaticUrl = (url) => {
  if (!url) return ''
  if (url.startsWith('http://') || url.startsWith('https://')) return url
  if (url.startsWith('/static')) {
    return `${backendOrigin}${url}`
  }
  return url
}

const userAvatar = computed(() => {
  const src = currentUser.value?.avatar_url || ''
  return normalizeStaticUrl(src) || `https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png`
})

// 统计数据
const stats = reactive({
  totalUsers: 0,
  adminUsers: 0,
  sensitiveWords: 0,
  sentencePairs: 0
})

// 折线图相关
const chartRef = ref(null)
const chartInstance = ref(null)

// 生成模拟活跃数据
const generateActivityData = () => {
  const dates = []
  const data = []
  const today = new Date()

  for (let i = 29; i >= 0; i--) {
    const date = new Date(today)
    date.setDate(date.getDate() - i)
    dates.push(date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' }))
    // 生成随机活跃次数 (20-150之间)
    data.push(Math.floor(Math.random() * 130) + 20)
  }

  return { dates, data }
}

// 个人资料
const profileDialogVisible = ref(false)
const profileLoading = ref(false)
const profileFormRef = ref(null)
const profileForm = reactive({
  username: '',
  email: '',
  bio: ''
})
const profileRules = {
  bio: [
    { max: 500, message: '个人简介不超过 500 字', trigger: 'blur' }
  ]
}

// 头像上传相关状态
const uploading = ref(false)
const avatarPreview = ref('')
const profileUser = ref({ id: null, username: '', email: '', avatar_url: '', bio: '' })

/**
 * 同步当前用户信息到内存与本地缓存，保证头像及时更新
 * @param {Record<string, any>} nextUser 将要保存的用户对象
 * @returns {void}
 */
const syncCurrentUser = (nextUser = {}) => {
  const merged = { ...(currentUser.value || {}), ...nextUser }
  currentUser.value = merged
  localStorage.setItem('user', JSON.stringify(merged))
}

const handleMenuSelect = (index) => {
  activeMenu.value = index
}

const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      showProfileDialog()
      break
    case 'logout':
      handleLogout()
      break
  }
}

const showProfileDialog = async () => {
  try {
    const response = await auth.getProfile()
    const user = response.data.user
    profileUser.value = {
      id: user.id,
      username: user.username,
      email: user.email,
      avatar_url: normalizeStaticUrl(user.avatar_url || ''),
      bio: user.bio || ''
    }
    syncCurrentUser({
      id: profileUser.value.id,
      username: profileUser.value.username,
      email: profileUser.value.email,
      avatar_url: profileUser.value.avatar_url,
      bio: profileUser.value.bio,
      role: user.role
    })
    avatarPreview.value = ''
    profileForm.username = profileUser.value.username
    profileForm.email = profileUser.value.email
    profileForm.bio = profileUser.value.bio
    profileDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

/**
 * 头像上传前校验：类型与大小，并生成本地预览
 * @param {File} file 待上传文件
 * @returns {boolean} 是否通过
 */
const beforeAvatarUpload = (file) => {
  const isAllowedType = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isAllowedType) {
    ElMessage.error('仅支持 JPG/PNG 格式')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB')
    return false
  }
  const reader = new FileReader()
  reader.onload = (e) => {
    avatarPreview.value = e.target.result
  }
  reader.readAsDataURL(file)
  return true
}

/**
 * 自定义头像上传：调用后端接口上传并刷新资料
 * @param {{ file: File, onSuccess?: Function, onError?: Function }} options element-plus http-request 形参
 * @returns {Promise<void>}
 */
const customAvatarUpload = async (options) => {
  const { file, onSuccess, onError } = options
  uploading.value = true
  try {
    const formData = new FormData()
    formData.append('avatar', file)
    if (auth.uploadAvatar) {
      const resp = await auth.uploadAvatar(formData)
      const newUrl = normalizeStaticUrl(resp?.data?.avatar_url || '')
      if (newUrl) {
        avatarPreview.value = newUrl
        syncCurrentUser({ avatar_url: newUrl })
      }
    } else {
      await auth.updateProfile(formData)
    }
    ElMessage.success('头像已上传')
    await showProfileDialog()
    onSuccess && onSuccess({}, file)
  } catch (e) {
    ElMessage.error('头像上传失败，后端暂未提供该能力')
    onError && onError(e)
  } finally {
    uploading.value = false
  }
}
const handleUpdateProfile = async () => {
  profileFormRef.value.validate(async (valid) => {
    if (!valid) return
      profileLoading.value = true
      try {
      await auth.updateProfile({ bio: profileForm.bio })
      // 同步本地缓存
      syncCurrentUser({ bio: profileForm.bio })
        ElMessage.success('个人资料更新成功')
        profileDialogVisible.value = false
      } catch (error) {
      ElMessage.error(error?.response?.data?.message || '更新失败')
      } finally {
        profileLoading.value = false
    }
  })
}

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '确认退出', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await auth.logout()
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    ElMessage.success('已退出登录')
    router.push('/login')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('退出登录失败')
    }
  }
}

const fetchStats = async () => {
  try {
    // 获取用户统计
    const usersResponse = await admin.getUsers({ per_page: 1 })
    stats.totalUsers = usersResponse.data.pagination.total

    const adminUsersResponse = await admin.getUsers({ role: 'admin', per_page: 1 })
    stats.adminUsers = adminUsersResponse.data.pagination.total

    // 获取敏感词统计
    const wordsResponse = await admin.getSensitiveWords({ per_page: 1 })
    stats.sensitiveWords = wordsResponse.data.pagination.total

    // 获取句子对统计
    const pairsResponse = await admin.getSentencePairs({ per_page: 1 })
    stats.sentencePairs = pairsResponse.data.pagination.total
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 初始化折线图
const initActivityChart = () => {
  nextTick(() => {
    if (chartRef.value && !chartInstance.value) {
      chartInstance.value = echarts.init(chartRef.value)
      const { dates, data } = generateActivityData()

      const option = {
        title: {
          text: '最近30天系统活跃次数',
          left: 'center',
          textStyle: {
            color: '#7c3aed',
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#7c3aed',
          borderWidth: 1,
          textStyle: {
            color: '#333'
          },
          formatter: function (params) {
            return `${params[0].name}<br/>活跃次数: ${params[0].value}`
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLine: {
            lineStyle: {
              color: '#7c3aed'
            }
          },
          axisLabel: {
            color: '#666',
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            lineStyle: {
              color: '#7c3aed'
            }
          },
          axisLabel: {
            color: '#666'
          },
          splitLine: {
            lineStyle: {
              color: '#e5e5e5'
            }
          }
        },
        series: [
          {
            name: '活跃次数',
            type: 'line',
            data: data,
            smooth: true,
            lineStyle: {
              color: '#7c3aed',
              width: 3
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(167, 139, 250, 0.3)'
                  },
                  {
                    offset: 1,
                    color: 'rgba(167, 139, 250, 0.05)'
                  }
                ]
              }
            },
            itemStyle: {
              color: '#7c3aed',
              borderColor: '#fff',
              borderWidth: 2
            },
            emphasis: {
              itemStyle: {
                color: '#5b21b6',
                borderColor: '#fff',
                borderWidth: 3,
                shadowColor: 'rgba(91, 33, 182, 0.3)',
                shadowBlur: 10
              }
            },
            symbol: 'circle',
            symbolSize: 6
          }
        ]
      }

      chartInstance.value.setOption(option)

      // 监听窗口大小变化，重新渲染图表
      const resizeHandler = () => {
        chartInstance.value && chartInstance.value.resize()
      }
      window.addEventListener('resize', resizeHandler)

      onUnmounted(() => {
        window.removeEventListener('resize', resizeHandler)
        if (chartInstance.value) {
          chartInstance.value.dispose()
          chartInstance.value = null
        }
      })
    }
  })
}

onMounted(() => {
  // 检查用户权限
  const user = JSON.parse(localStorage.getItem('user') || '{}')
  if (user.role !== 'admin') {
    ElMessage.error('无权限访问管理后台')
    router.push('/')
    return
  }
  
  fetchStats()
  initActivityChart()

  /**
   * 跨标签页同步头像或资料变更，维持导航栏一致
   */
  const handleStorage = (event) => {
    if (event.key === 'user' && event.newValue) {
      try {
        currentUser.value = JSON.parse(event.newValue)
      } catch {
        // ignore parse error
      }
    }
  }
  window.addEventListener('storage', handleStorage)
  onUnmounted(() => {
    window.removeEventListener('storage', handleStorage)
  })
})
</script>

<style scoped>
/* CSS变量定义 */
.admin-dashboard {
  --primary: #a78bfa;
  --primary-light: #ddd6fe;
  --primary-dark: #7c3aed;
  --primary-strong: #7c3aed;
}

.profile-content {
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-gap: 24px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-wrapper {
  margin-bottom: 12px;
}

.avatar-actions .hint {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

.profile-form {
  width: 100%;
}

.header {
  background: var(--primary-light);
  border-bottom: 1px solid var(--primary);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.header-left h2 {
  margin: 0;
  color: var(--primary-dark);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.system-logo {
  width: 40px;
  height: 40px;
  object-fit: contain;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: var(--primary);
  color: white;
}

.username {
  margin: 0 8px;
  color: inherit;
}

.sidebar {
  background: var(--primary-light);
  border-right: 1px solid var(--primary);
}

.sidebar-menu {
  border-right: none;
  background: transparent;
}

.sidebar-menu :deep(.el-menu-item.is-active) {
  background-color: var(--primary) !important;
  color: white !important;
}

.sidebar-menu :deep(.el-menu-item:hover) {
  background-color: var(--primary) !important;
  color: white !important;
}

.main-content {
  background: var(--primary-light);
  padding: 20px;
}

.dashboard-overview h3 {
  margin-bottom: 20px;
  color: var(--primary-dark);
}

.stats-cards {
  margin-bottom: 30px;
}

.stat-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(167, 139, 250, 0.15);
  border: 1px solid var(--primary);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px 0 rgba(167, 139, 250, 0.25);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 10px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: #fff;
  transition: all 0.3s ease;
}

.user-icon {
  background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
}

.admin-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.word-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.data-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: var(--primary-dark);
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: var(--primary);
  margin-top: 5px;
  font-weight: 500;
}

.recent-activity {
  margin-top: 30px;
}

.recent-activity h4 {
  margin-bottom: 15px;
  color: var(--primary-dark);
}

.activity-chart-container {
  padding: 20px;
  height: 300px;
  background: white;
  border-radius: 8px;
  border: 1px solid var(--primary);
}

.activity-placeholder {
  padding: 40px 0;
  color: var(--primary);
}
</style>
